<template>
  <div>
    <a-card title="酒店位置管理">
      <a-form
        :model="locationForm"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
        :disabled="!editing"
      >
        <a-form-item label="详细地址">
          <a-input v-model:value="locationForm.address" />
        </a-form-item>
        
        <a-form-item label="城市">
          <a-input v-model:value="locationForm.city" />
        </a-form-item>
        
        <a-form-item label="省份/州">
          <a-input v-model:value="locationForm.province" />
        </a-form-item>
        
        <a-form-item label="邮编">
          <a-input v-model:value="locationForm.postalCode" />
        </a-form-item>
        
        <a-form-item label="国家">
          <a-input v-model:value="locationForm.country" />
        </a-form-item>
        
        <a-form-item label="经度">
          <a-input-number v-model:value="locationForm.longitude" style="width: 100%;" :precision="6" />
        </a-form-item>
        
        <a-form-item label="纬度">
          <a-input-number v-model:value="locationForm.latitude" style="width: 100%;" :precision="6" />
        </a-form-item>
        
        <a-divider>周边交通</a-divider>
        
        <div class="transportation-section">
          <div v-for="(item, index) in locationForm.transportation" :key="index" class="transportation-item">
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item label="类型" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
                  <a-select v-model:value="item.type">
                    <a-select-option value="airport">机场</a-select-option>
                    <a-select-option value="train">火车站</a-select-option>
                    <a-select-option value="subway">地铁站</a-select-option>
                    <a-select-option value="bus">公交站</a-select-option>
                    <a-select-option value="other">其他</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="名称" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
                  <a-input v-model:value="item.name" />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="距离" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
                  <a-input-number v-model:value="item.distance" :min="0" style="width: 100%;" />
                </a-form-item>
              </a-col>
              <a-col :span="5">
                <a-form-item label="单位" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
                  <a-select v-model:value="item.unit">
                    <a-select-option value="km">公里</a-select-option>
                    <a-select-option value="m">米</a-select-option>
                    <a-select-option value="min">分钟</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="1">
                <a-button 
                  type="text" 
                  danger 
                  @click="removeTransportation(index)"
                  :disabled="!editing"
                >
                  <delete-outlined />
                </a-button>
              </a-col>
            </a-row>
          </div>
          
          <a-button 
            type="dashed" 
            block 
            @click="addTransportation" 
            :disabled="!editing"
          >
            <plus-outlined /> 添加交通信息
          </a-button>
        </div>
        
        <a-divider>周边设施</a-divider>
        
        <div class="attractions-section">
          <div v-for="(item, index) in locationForm.attractions" :key="index" class="attraction-item">
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item label="设施" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
                  <a-input v-model:value="item.name" placeholder="请输入设施名称" />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="类型" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
                  <a-select v-model:value="item.type" placeholder="选择类型">
                    <a-select-option value="shopping">购物中心</a-select-option>
                    <a-select-option value="coffee">餐饮场所</a-select-option>
                    <a-select-option value="landmark">地标建筑</a-select-option>
                    <a-select-option value="park">公园景区</a-select-option>
                    <a-select-option value="bank">银行金融</a-select-option>
                    <a-select-option value="medicine">医疗机构</a-select-option>
                    <a-select-option value="entertainment">娱乐场所</a-select-option>
                    <a-select-option value="museum">博物馆</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                  <a-form-item label="距离" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
                  <a-input-number v-model:value="item.distance" :min="0" style="width: 100%" placeholder="距离值" />
                </a-form-item>
              </a-col>
              <a-col :span="5">
                <a-form-item label="单位" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
                  <a-select v-model:value="item.unit">
                    <a-select-option value="km">公里</a-select-option>
                    <a-select-option value="m">米</a-select-option>
                    <a-select-option value="min">分钟</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              
              <a-col :span="1">
                <a-button 
                  type="text" 
                  danger 
                  @click="removeAttraction(index)"
                  :disabled="!editing"
                >
                  <delete-outlined />
                </a-button>
              </a-col>
            </a-row>
          </div>
          
          <a-button 
            type="dashed" 
            block 
            @click="addAttraction" 
            :disabled="!editing"
          >
            <plus-outlined /> 添加周边设施
          </a-button>
        </div>
        
        <a-divider>地图预览</a-divider>
        
        <div class="map-container">
          <div id="baiduMap" style="width: 100%; height: 100%;"></div>
        </div>
      </a-form>
      
      <div style="margin-left: 16.6667%; margin-top: 20px;">
        <a-button v-if="!editing" type="primary" @click="editing = true">编辑</a-button>
        <a-button v-else type="primary" @click="saveLocation" style="margin-right: 8px;">保存</a-button>
        <a-button v-if="editing" @click="cancelEdit">取消</a-button>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { message } from 'ant-design-vue';
import { 
  PlusOutlined, 
  DeleteOutlined,
  EnvironmentOutlined
} from '@ant-design/icons-vue';
import { 
  apiGetHotelLocation, 
  apiCreateHotelLocation, 
  apiUpdateHotelLocation 
} from '@/api/admin-api';
import { useHotelStore } from '@/stores/hotelStrore';

// 定义类型接口
interface Transportation {
  type: string;
  name: string;
  distance: number;
  unit: string;
}

interface Attraction {
  name: string;
  type: string;
  distance: number;
  unit: string;
}

interface LocationData {
  id?: string;
  hotelId: string;
  address: string;
  city: string;
  province: string;
  postalCode: string;
  country: string;
  longitude: number;
  latitude: number;
  transportation: Transportation[];
  attractions: Attraction[];
}

// 获取store
const hotelStore = useHotelStore();

// 编辑状态
const editing = ref(false);

// 初始空数据结构
const emptyLocationData: LocationData = {
  hotelId: '',
  address: '',
  city: '',
  province: '',
  postalCode: '',
  country: '',
  longitude: 0,
  latitude: 0,
  transportation: [],
  attractions: []
};

// 原始数据，用于取消编辑时恢复
const originalLocation = ref<LocationData>({...emptyLocationData});

// 表单数据
const locationForm = ref<LocationData>({...emptyLocationData});

// 百度地图实例
let map: any = null;
let marker: any = null;
let geocoder: any = null;

// 初始化地图
const initMap = () => {
  // 确保BMap已加载
  if (typeof BMap === 'undefined') {
    console.error('Baidu Map not loaded');
    return;
  }

  // 创建地图实例
  map = new BMap.Map('baiduMap');
  
  // 创建地理编码器实例
  geocoder = new BMap.Geocoder();

  // 初始中心点（如果有经纬度则使用已有的，否则默认使用北京）
  const point = locationForm.value.longitude && locationForm.value.latitude
    ? new BMap.Point(locationForm.value.longitude, locationForm.value.latitude)
    : new BMap.Point(116.404, 39.915);

  // 初始化地图
  map.centerAndZoom(point, 15);
  
  // 添加地图控件
  map.addControl(new BMap.NavigationControl());
  map.addControl(new BMap.ScaleControl());
  map.enableScrollWheelZoom();

  // 如果有经纬度，添加标记
  if (locationForm.value.longitude && locationForm.value.latitude) {
    addMarker(point);
  }

  // 点击地图事件
  map.addEventListener('click', (e: any) => {
    if (!editing.value) return;
    const pt = e.point;
    updateLocationByPoint(pt);
  });
};

// 添加标记
const addMarker = (point: any) => {
  if (marker) {
    map.removeOverlay(marker);
  }
  marker = new BMap.Marker(point);
  map.addOverlay(marker);
  marker.setAnimation(window.BMAP_ANIMATION_BOUNCE);
};

// 根据地址解析坐标
const geocodeAddress = (address: string) => {
  if (!geocoder) return;
  
  geocoder.getPoint(address, (point: any) => {
    if (point) {
      locationForm.value.longitude = point.lng;
      locationForm.value.latitude = point.lat;
      map.centerAndZoom(point, 15);
      addMarker(point);
    } else {
      message.error('无法解析该地址的坐标');
    }
  });
};

// 根据坐标更新地址信息
const updateLocationByPoint = (point: any) => {
  if (!geocoder) return;
  
  addMarker(point);
  locationForm.value.longitude = point.lng;
  locationForm.value.latitude = point.lat;

  geocoder.getLocation(point, (result: any) => {
    if (result) {
      const addressComponents = result.addressComponents;
      locationForm.value.address = result.address;
      locationForm.value.city = addressComponents.city;
      locationForm.value.province = addressComponents.province;
      locationForm.value.postalCode = getPostalCode(addressComponents);
      locationForm.value.country = addressComponents.country || '中国';
    }
  });
};

// 获取邮编信息
const getPostalCode = (addressComponents: any) => {
  // 尝试从百度地图返回的信息中获取邮编
  // 如果没有邮编信息，则根据城市和地区查询
  if (addressComponents.postcode) {
    return addressComponents.postcode;
  }
  
  // 如果百度地图没有返回邮编，可以调用邮编查询API
  // 这里使用城市+区域作为关键词进行邮编查询
  const cityAndDistrict = `${addressComponents.city}${addressComponents.district}`;
  queryPostalCode(cityAndDistrict);
  
  return '';
};

// 查询邮编API
const queryPostalCode = (address: string) => {
  // 可以使用百度地图周边信息查询或其他邮编查询API
  // 这里使用百度地图的周边信息搜索
  if (!map) return;
  
  const local = new BMap.LocalSearch(map, {
    onSearchComplete: (results: any) => {
      if (results && results.getNumPois() > 0) {
        // 尝试从搜索结果中提取邮编信息
        const firstResult = results.getPoi(0);
        if (firstResult && firstResult.address && firstResult.address.includes('邮编')) {
          const postalCodeMatch = firstResult.address.match(/邮编[：:]\s*(\d{6})/);
          if (postalCodeMatch && postalCodeMatch[1]) {
            locationForm.value.postalCode = postalCodeMatch[1];
          }
        }
      }
    }
  });
  
  // 搜索邮局或邮编相关信息
  local.search(address + " 邮编");
};

// 监听地址变化
watch(() => locationForm.value.address, (newAddress) => {
  if (newAddress && editing.value) {
    geocodeAddress(newAddress);
  }
});

// 加载酒店位置数据
const fetchLocationData = async () => {
  try {
    if (!hotelStore.safeHotelId) {
      console.error("酒店ID为空，无法获取位置数据");
      message.error('酒店ID未设置，无法加载位置信息');
      return;
    }
    
    const response = await apiGetHotelLocation(hotelStore.safeHotelId);
    console.log("位置数据响应:", response);
    
    if (response && response.data) {
      console.log("获取位置数据成功:", response.data);
      
      // 处理可能是字符串的transportation和attractions
      const locationData = { ...response.data };
      
      // 处理交通信息数据
      if (locationData.transportation) {
        if (typeof locationData.transportation === 'string') {
          try {
            locationData.transportation = JSON.parse(locationData.transportation);
          } catch (e) {
            console.error('解析交通信息失败:', e);
            locationData.transportation = [];
          }
        } else if (!Array.isArray(locationData.transportation)) {
          locationData.transportation = [];
        }
      } else {
        locationData.transportation = [];
      }
      
      // 处理周边设施数据
      if (locationData.attractions) {
        if (typeof locationData.attractions === 'string') {
          try {
            locationData.attractions = JSON.parse(locationData.attractions);
          } catch (e) {
            console.error('解析周边设施信息失败:', e);
            locationData.attractions = [];
          }
        } else if (!Array.isArray(locationData.attractions)) {
          locationData.attractions = [];
        }
      } else {
        locationData.attractions = [];
      }
      
      // 更新数据
      Object.assign(originalLocation.value, locationData);
      Object.assign(locationForm.value, JSON.parse(JSON.stringify(originalLocation.value)));
      
      // 如果有经纬度，更新地图
      if (locationForm.value.longitude && locationForm.value.latitude && map) {
        const point = new BMap.Point(locationForm.value.longitude, locationForm.value.latitude);
        map.centerAndZoom(point, 15);
        addMarker(point);
      }
    } else {
      console.warn("位置数据格式不正确或为空");
    }
  } catch (error) {
    message.error('加载酒店位置信息失败');
    console.error('加载酒店位置信息失败:', error);
  }
};

// 添加交通信息
function addTransportation() {
  locationForm.value.transportation.push({
    type: 'subway',
    name: '',
    distance: 0,
    unit: 'km'
  });
}

// 删除交通信息
function removeTransportation(index: number) {
  locationForm.value.transportation.splice(index, 1);
}

// 添加景点信息
function addAttraction() {
  locationForm.value.attractions.push({
    name: '',
    type: 'shopping',
    distance: 0,
    unit: 'm'
  });
}

// 删除景点信息
function removeAttraction(index: number) {
  locationForm.value.attractions.splice(index, 1);
}

// 保存位置信息
const saveLocation = async () => {
  try {
    // 检查酒店ID是否存在
    if (!hotelStore.safeHotelId) {
      message.error('酒店ID未设置，无法保存位置信息');
      return;
    }

    // 格式化数据
    const dataToSave = { ...locationForm.value };
    dataToSave.hotelId = hotelStore.safeHotelId;
    
    // 验证数据
    if (!dataToSave.address.trim()) {
      message.error('请填写酒店地址');
      return;
    }
    
    // 过滤掉空的交通和设施信息
    if (Array.isArray(dataToSave.transportation)) {
      dataToSave.transportation = dataToSave.transportation.filter(item => 
        item && item.name && item.name.trim() !== ''
      );
    }
    
    if (Array.isArray(dataToSave.attractions)) {
      dataToSave.attractions = dataToSave.attractions.filter(item => 
        item && item.name && item.name.trim() !== ''
      );
    }
    
    let response:any ;
    if (originalLocation.value.id) {
      response = await apiUpdateHotelLocation(hotelStore.safeHotelId, dataToSave);
    } else {
      response = await apiCreateHotelLocation(hotelStore.safeHotelId, dataToSave);
    }
    
    if (response && response.code === 200) {
      message.success('位置信息已保存');
      
      // 处理返回的数据
      const savedData = { ...response.data };
      
      // 处理可能是字符串的交通信息和周边设施数据
      if (savedData.transportation) {
        if (typeof savedData.transportation === 'string') {
          try {
            savedData.transportation = JSON.parse(savedData.transportation);
          } catch (e) {
            console.error('解析返回的交通信息失败:', e);
            savedData.transportation = [];
          }
        } else if (!Array.isArray(savedData.transportation)) {
          savedData.transportation = [];
        }
      }
      
      if (savedData.attractions) {
        if (typeof savedData.attractions === 'string') {
          try {
            savedData.attractions = JSON.parse(savedData.attractions);
          } catch (e) {
            console.error('解析返回的设施信息失败:', e);
            savedData.attractions = [];
          }
        } else if (!Array.isArray(savedData.attractions)) {
          savedData.attractions = [];
        }
      }
      
      Object.assign(originalLocation.value, savedData);
      Object.assign(locationForm.value, JSON.parse(JSON.stringify(originalLocation.value)));
      editing.value = false;
    } else {
      message.error(response?.data?.msg || '保存位置信息失败');
    }
  } catch (error) {
    message.error('保存位置信息失败');
    console.error('保存位置信息失败:', error);
  }
};

// 取消编辑
const cancelEdit = () => {
  Object.assign(locationForm.value, JSON.parse(JSON.stringify(originalLocation.value)));
  editing.value = false;
  
  // 恢复地图标记到原始位置
  if (locationForm.value.longitude && locationForm.value.latitude) {
    const point = new BMap.Point(locationForm.value.longitude, locationForm.value.latitude);
    map.centerAndZoom(point, 15);
    addMarker(point);
  }
};

// 组件挂载时加载数据和初始化地图
onMounted(async () => {
  console.log("LocationManage组件挂载");
  
  // 确保先获取酒店信息
  if (!hotelStore.isInitialized || !hotelStore.safeHotelId) {
    console.log("等待获取酒店信息...");
    await hotelStore.getHotelInfo();
  }
  
  // 动态加载百度地图脚本
  const script = document.createElement('script');
  script.src = `https://api.map.baidu.com/api?v=3.0&ak=URTOk3aJ8lIH1VLPSTeDWJkSGttQkphr&callback=initBaiduMap`;
  script.async = true;
  document.body.appendChild(script);
  
  // 全局回调函数
  window.initBaiduMap = () => {
    initMap();
    if (hotelStore.safeHotelId) {
      console.log("开始加载位置数据，酒店ID:", hotelStore.safeHotelId);
      fetchLocationData();
    } else {
      console.warn('酒店ID未设置，无法加载位置数据');
      message.warning('请先选择或创建酒店');
    }
  };
});
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 400px;
  margin-bottom: 24px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.transportation-section,
.attractions-section {
  margin-bottom: 24px;
}

.transportation-item,
.attraction-item {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 4px;
}
</style>